package com.evil.log.config;

import cn.hutool.extra.servlet.JakartaServletUtil;
import com.evil.common.core.enums.BaseEnum;
import com.evil.common.core.exception.BusinessException;
import com.evil.common.core.util.ServletUtils;
import com.evil.common.family.constant.AppConstant;
import com.evil.common.log.constant.LogConstant;
import com.evil.common.redis.util.RedisKeyUtil;
import feign.RequestInterceptor;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author liyang
 * @date 2022-08-08 00:00
 */
@Slf4j
@Configuration
public class FeignHeaderConfiguration {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attrs != null) {
                HttpServletRequest request = attrs.getRequest();

                // cookie
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        requestTemplate.header(cookie.getName(), cookie.getValue());
                    }
                }

                // header
                ServletUtils.getHeaders(request, requestTemplate::header);

                // requestUuid
                String requestUuid = RedisKeyUtil.requestUuid(request);
                if (StringUtils.isBlank(requestUuid)) {
                    throw new BusinessException(BaseEnum.RUN_ERROR, (Object) "requestUuid cannot be null");
                }

                // 请求日志
                Long requestLogId = (Long) request.getAttribute(LogConstant.HEADER_REQUEST_LOG_ID);
                if (null != requestLogId) {
                    requestTemplate.header(LogConstant.HEADER_REQUEST_LOG_ID, Long.toString(requestLogId));
                }

                // 自定义IP字段，防止转发服务时丢失
                requestTemplate.header(AppConstant.HEADER_REAL_IP_KEY, JakartaServletUtil.getClientIP(request));
            }
        };
    }
}
